<template>
  <view class="feedback-container">
    <scroll-view scroll-y class="scroll-view">
      <view class="content-area">
        <!-- 询价标题 -->
        <view class="form-section">
          <view class="form-label">询价标题</view>
          <view class="input-container">
            <uv-input
              v-model="formData.title"
              placeholder="请输入问题"
              :border="false"
              :clearable="true"
              :custom-style="inputStyle"
            ></uv-input>
          </view>
        </view>

        <!-- 上传图片 -->
        <view class="form-section">
          <view class="form-label">上传图片</view>
          <view class="upload-container">
            <view 
              class="upload-item" 
              v-for="(image, index) in formData.images" 
              :key="index"
            >
              <image :src="image" mode="aspectFill" class="uploaded-image" />
              
              <!-- 上传状态指示器 -->
              <view v-if="!uploadedImageUrls[index]" class="upload-status">
                <uv-icon name="loading" size="16" color="#FF6B35" class="loading-icon"></uv-icon>
                <text class="status-text">上传中</text>
              </view>
              
              <view class="delete-btn" @click="deleteImage(index)">
                <uv-icon name="close" size="16" :color="'#fff'"></uv-icon>
              </view>
            </view>
            
            <view class="upload-btn" @click="chooseImage" v-if="formData.images.length < 3">
              <uv-icon name="plus" size="32" color="#999"></uv-icon>
            </view>
          </view>
          <view class="upload-tip">最多上传3张图片</view>
        </view>

        <!-- 问题描述 -->
        <view class="form-section">
          <view class="form-label">问题描述</view>
          <view class="textarea-container">
            <uv-textarea
              v-model="formData.desc"
              placeholder="请输入内容"
              :maxlength="500"
              :show-count="true"
              :custom-style="textareaStyle"
            ></uv-textarea>
          </view>
        </view>
      </view>
    </scroll-view>

    <!-- 提交按钮 -->
    <view class="submit-section">
      <uv-button
        type="primary"
        text="提交问题"
        size="large"
        :custom-style="submitButtonStyle"
        @click="submitFeedback"
      ></uv-button>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import { useRequest } from '@/api'
const { API_FEEDBACK_LIST } = useRequest()
import { UserInfoManager } from '@/utils/userInfo'

// 表单数据
const formData = reactive({
  title: '',
  images: [] as string[],
  desc: ''
})

// 存储上传后的图片URL
const uploadedImageUrls = ref<string[]>([])

// 输入框样式
const inputStyle = {
  backgroundColor: '#f8f9fa',
  borderRadius: '12rpx',
  padding: '24rpx',
  fontSize: '28rpx',
  color: '#333'
}

// 文本域样式
const textareaStyle = {
  backgroundColor: '#f8f9fa',
  borderRadius: '12rpx',
  padding: '24rpx',
  fontSize: '28rpx',
  color: '#333',
  minHeight: '200rpx'
}

// 提交按钮样式（参考设置页面）
const submitButtonStyle = {
  backgroundColor: '#FF6B35',
  borderColor: '#FF6B35',
  borderRadius: '24rpx',
  height: '88rpx',
  fontSize: '32rpx',
  fontWeight: '600'
}

// 选择图片
const chooseImage = () => {
  const remainingCount = 3 - formData.images.length
  if (remainingCount <= 0) {
    uni.showToast({
      title: '最多只能上传3张图片',
      icon: 'none'
    })
    return
  }

  uni.chooseImage({
    count: remainingCount,
    sizeType: ['original', 'compressed'],
    sourceType: ['album', 'camera'],
    success: (res) => {
      const tempFilePaths = res.tempFilePaths
      // 先添加到临时图片列表
      formData.images = [...formData.images, ...tempFilePaths].slice(0, 3)
      console.log('选择的图片:', tempFilePaths)
      
      // 自动上传新选择的图片
      if (Array.isArray(tempFilePaths)) {
        tempFilePaths.forEach(filePath => {
          uploadFile(filePath)
        })
      }
    },
    fail: (err) => {
      console.error('选择图片失败', err)
      uni.showToast({
        title: '选择图片失败',
        icon: 'none'
      })
    }
  })
}

// 上传单个文件
const uploadFile = async (filePath: string) => {
  uni.showLoading({ title: '上传中...' })
  
  try {
    const uploadRes = await uni.uploadFile({
      url: import.meta.env.VITE_APP_API_BASEURL + '/api/index/upload',
      filePath: filePath,
      name: 'file',
      formData: {
        type: 'feedback' // 文件类型标识
      },
      success: (res) => {
        try {
          const data = JSON.parse(res.data)
          console.log(data)
          if (data.code === 1) {
            // 上传成功，将返回的URL添加到已上传列表
            uploadedImageUrls.value.push(data.data.fullurl)
            uni.showToast({
              title: '上传成功',
              icon: 'success'
            })
          } else {
            uni.showToast({
              title: data.msg || '上传失败',
              icon: 'none'
            })
          }
        } catch (e) {
          console.error('解析上传响应失败:', e)
          uni.showToast({
            title: '上传失败',
            icon: 'none'
          })
        }
      },
      fail: (err) => {
        console.error('上传失败:', err)
        uni.showToast({
          title: '上传失败',
          icon: 'none'
        })
      }
    })
  } catch (error) {
    console.error('上传异常:', error)
    uni.showToast({
      title: '上传异常',
      icon: 'none'
    })
  } finally {
    uni.hideLoading()
  }
}

// 删除图片
const deleteImage = (index: number) => {
  uni.showModal({
    title: '确认删除',
    content: '确定要删除这张图片吗？',
    success: (res) => {
      if (res.confirm) {
        // 同时删除临时图片和已上传的图片
        formData.images.splice(index, 1)
        uploadedImageUrls.value.splice(index, 1)
        uni.showToast({
          title: '删除成功',
          icon: 'success'
        })
      }
    }
  })
}

// 提交反馈
const submitFeedback = async () => {
  // 验证表单
  if (!formData.title.trim()) {
    uni.showToast({ title: '请输入询价标题', icon: 'none' })
    return
  }

  if (!formData.desc.trim()) {
    uni.showToast({ title: '请输入问题描述', icon: 'none' })
    return
  }

  // 检查是否有图片正在上传
  if (formData.images.length > 0 && uploadedImageUrls.value.length < formData.images.length) {
    uni.showToast({ title: '请等待图片上传完成', icon: 'none' })
    return
  }

  uni.showLoading({ title: '提交中...' })
  
  try {
    const params = {
      isdriver: UserInfoManager.lastrole(),
      title: formData.title,
      desc: formData.desc,
      feedback_images: uploadedImageUrls.value.join(',')
    }
    
    const res = await API_FEEDBACK_LIST(params)
    if (res.code === 1) {
      uni.showToast({ title: '提交成功', icon: 'success' })
      setTimeout(() => {
        uni.navigateBack()
      }, 500)
    }
  } catch (error) {
   
  } finally {
    uni.hideLoading()
  }
}
</script>

<style lang="scss" scoped>
.feedback-container {
  height: 100vh;
  background: #f8f9fa;
  display: flex;
  flex-direction: column;
}

.scroll-view {
  flex: 1;
  background: #f8f9fa;
}

.content-area {
  padding: 32rpx;
}

// 表单区域
.form-section {
  background: #fff;
  border-radius: 16rpx;
  padding: 32rpx;
  margin-bottom: 24rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.05);

  .form-label {
    font-size: 32rpx;
    color: #333;
    font-weight: 500;
    margin-bottom: 24rpx;
  }

  .input-container {
    width: 100%;
  }

  .textarea-container {
    width: 100%;
  }

  .upload-container {
    display: flex;
    flex-wrap: wrap;
    gap: 24rpx;
    margin-bottom: 16rpx;

          .upload-item {
        position: relative;
        width: 160rpx;
        height: 160rpx;
        border-radius: 12rpx;
        overflow: hidden;

        .uploaded-image {
          width: 100%;
          height: 100%;
        }

        .upload-status {
          position: absolute;
          top: 0;
          left: 0;
          right: 0;
          bottom: 0;
          background-color: rgba(0, 0, 0, 0.6);
          display: flex;
          flex-direction: column;
          justify-content: center;
          align-items: center;
          border-radius: 12rpx;

          .loading-icon {
            animation: rotate 1s linear infinite;
            margin-bottom: 8rpx;
          }

          .status-text {
            font-size: 20rpx;
            color: #fff;
          }
        }

        .delete-btn {
          position: absolute;
          top: 8rpx;
          right: 8rpx;
          width: 32rpx;
          height: 32rpx;
          background: rgba(0, 0, 0, 0.6);
          border-radius: 16rpx;
          display: flex;
          align-items: center;
          justify-content: center;
        }
      }

    .upload-btn {
      width: 160rpx;
      height: 160rpx;
      background: #f8f9fa;
      border: 2rpx dashed #ddd;
      border-radius: 12rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      transition: all 0.2s ease;

      &:active {
        background: #e9ecef;
        border-color: #adb5bd;
      }
    }
  }

  .upload-tip {
    font-size: 24rpx;
    color: #999;
    text-align: center;
  }
}

// 提交按钮区域（参考设置页面样式）
.submit-section {
  position: fixed;
  bottom: 0;
  left: 0;
  width: 100%;
  padding: 32rpx;
  background: #fff;
  box-shadow: 0 -2rpx 8rpx rgba(0, 0, 0, 0.05);
}

// 深度样式调整
:deep(.uv-input__input) {
  font-size: 28rpx !important;
  color: #333 !important;
}

:deep(.uv-input__placeholder) {
  color: #999 !important;
  font-size: 28rpx !important;
}

:deep(.uv-textarea__textarea) {
  font-size: 28rpx !important;
  color: #333 !important;
}

:deep(.uv-textarea__placeholder) {
  color: #999 !important;
  font-size: 28rpx !important;
}

:deep(.uv-textarea__count) {
  font-size: 24rpx !important;
  color: #999 !important;
}

// 旋转动画
@keyframes rotate {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}
</style>
